package com.hangxin.system.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.hangxin.system.util.GlobalUtil;

public class FileZipUploadServlet extends HttpServlet
{
	private static final long serialVersionUID = -7825355637448948879L;



	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}



	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存缓冲区，超过后写入临时文件
		factory.setSizeThreshold(10240000);// 10M
		// 设置临时文件存储位置
		String strname = "";
		String path = GlobalUtil.getProperty("path");
//		String softype = request.getParameter("softype");
		String base = path + "upfile/bill/";
		File file = new File(base);
		if (!file.exists())
		{
			file.mkdirs();
		}
		factory.setRepository(file);
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置单个文件的最大上传值
		upload.setFileSizeMax(10002400000l);// 100M
		// 设置整个request的最大值
		upload.setSizeMax(10002400000l);// 1000M
		upload.setHeaderEncoding("UTF-8");

		PrintWriter out = null;
		try
		{
			out = response.getWriter();
		} catch (IOException e)
		{
			e.printStackTrace();
		}

		try
		{
			List<?> items = upload.parseRequest(request);
			FileItem item = null;
			String fileName = null;
			for (int i = 0; i < items.size(); i++)
			{
				item = (FileItem) items.get(i);
				String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
				
				fileName = base + File.separator + newFileName+".zip";//上传文件
				// 保存文件
				if (!item.isFormField() && item.getName().length() > 0)
				{
					item.write(new File(fileName));
					// -------解压---------
					ZipFile zfile = null;
					OutputStream os = null;
					InputStream is = null;
					try
					{
						zfile = new ZipFile(fileName);
						Enumeration zList = zfile.entries();
						ZipEntry ze = null;
						byte[] buf = new byte[1024];

						while (zList.hasMoreElements())
						{
							// in ZipFile file get ZipEntry
							ze = (ZipEntry) zList.nextElement();
							 
							if (ze.isDirectory())
							{
								continue;
							}
							// ZipEntry para find InputStream,write OutputStream
							// OutputStream os=new BufferedOutputStream(new FileOutputStream(getRealFileName("d:\\", ze.getName())));
							String zename = ze.getName();
							 //判断路径是否存在,不存在则创建文件路径  
//				            File zefile = new File(zename.substring(0, zename.lastIndexOf('/')));  
//				            if(!zefile.exists()){  
//				            	new File(newFileName).mkdirs();  
//				            }
							String temp = null;
//							if (zename.lastIndexOf("/") > -1)
//							{
//								temp = zename.substring(zename.lastIndexOf("/"), zename.length());
//							} else
//							{
//								temp = "/" + zename;
//							}
							strname = newFileName;
							temp = "/" + zename.replace(zename.substring(0, zename.indexOf("/")), newFileName);
							try
							{
								os = new BufferedOutputStream(new FileOutputStream(getRealFileName(fileName.substring(0, fileName.lastIndexOf("\\")), temp)));
								is = new BufferedInputStream(zfile.getInputStream(ze));
								int readLen = 0;
								while ((readLen = is.read(buf, 0, 1024)) != -1)
								{
									os.write(buf, 0, readLen);
								}
							} catch (Exception e)
							{
								is.close();
								os.close();
							}
						}
					} catch (Exception e)
					{
						zfile.close();
					} finally
					{
						is.close();
						os.close();
						zfile.close();
					}
					// -------解压---------
					// --------删除-----------
					// File f = new File(fileName);
					// if (f.exists() && f.isFile())
					// {
					// f.delete();
					// }
					// --------删除-----------

				}
			}
//			strname = strname.substring(0, strname.length() - 1);
			out.print(strname);
		} catch (FileUploadException e)
		{
			e.printStackTrace();
			out.close();
		} catch (Exception e)
		{
			e.printStackTrace();
			out.close();
		} finally
		{
			out.close();
		}
	}



	private static File getRealFileName(String baseDir, String absFileName)
	{
		String[] dirs = absFileName.split("/");
		// System.out.println(dirs.length);
		File ret = new File(baseDir);
		// System.out.println(ret);
		if (dirs.length > 1)
		{
			for (int i = 0; i < dirs.length - 1; i++)
			{
				ret = new File(ret, dirs[i]);
			}
		}
		if (!ret.exists())
		{
			ret.mkdirs();
		}
		ret = new File(ret, dirs[dirs.length - 1]);
		return ret;
	}
}
